package com.zc.app.web.servlet;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zc on 2016/7/18.
 */
@WebServlet(name = "loginServlet", urlPatterns = "/login2")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
        req.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        String error = null;
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
        token.setRememberMe(true);
        try {
            subject.login(token);
            PrincipalCollection principalCollection = subject.getPrincipals();
        } catch (UnknownAccountException ex){
            error = "用户名/密码错误";
        } catch (IncorrectCredentialsException ex){
            error = "用户名/密码错误";
        } catch (AuthenticationException ex){
            error = "其它错误: " + ex.getMessage();
        }

        if(error != null){
            req.setAttribute("error", error);
            req.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("/WEB-INF/views/loginSuccess.jsp").forward(req, resp);
        }

    }
}
